package com.olap.starter.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.olap.starter.core.base.BaseService;
import com.olap.starter.mapper.TableConfigColumnMapper;
import com.olap.starter.pojo.TableConfig;
import com.olap.starter.pojo.TableConfigColumn;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author WBG
 * @since 2022-08-31
 */
@Service
@DS("online")
public class TableConfigColumnServices extends BaseService<TableConfigColumnMapper, TableConfigColumn> {
    /**
     * 分组表头id
     */
    private Map<String, Object> groupHeaderMap = new HashMap<>();

    public void saveList(List<TableConfigColumn> list, TableConfig tableConfig) {
        int version = getBaseMapper().getVersion(tableConfig.getUuid()) + 1;

        for (TableConfigColumn tableConfigColumn : list) {
            tableConfigColumn.setParentId(tableConfig.getId());
            tableConfigColumn.setTheme(tableConfig.getTheme());
            tableConfigColumn.setUuid(tableConfig.getUuid());
            tableConfigColumn.setVersion(version);
            tableConfigColumn.setId(null);
            Object groupHeader = groupHeaderMap.get(tableConfigColumn.getField());
            if (!ObjectUtils.isEmpty(groupHeader)) {
                tableConfigColumn.setParentFieldId(groupHeader.toString());
            }
        }
        update(new UpdateWrapper<TableConfigColumn>().eq("uuid", tableConfig.getUuid()).eq("theme", tableConfig.getTheme()).set("deleted", 1));
        for (TableConfigColumn tableConfigColumn : list) {
            save(tableConfigColumn);
        }
    }

    public void setGroupHeaderMap(Map<String, Object> groupHeaderMap) {
        this.groupHeaderMap = groupHeaderMap;
    }

    public Map<String, Object> getGroupHeaderMap() {
        return groupHeaderMap;
    }

    /**
     * 根据表配置id查询表头字段配置
     * @param id
     * @return
     */
    public List<TableConfigColumn> queryByParentId(String id) {
        LambdaQueryWrapper<TableConfigColumn> wrap = Wrappers.lambdaQuery(TableConfigColumn.class)
                .eq(TableConfigColumn::getParentId, Long.parseLong(id))
                .eq(TableConfigColumn::getColumnAuth, StringPool.ONE)
                .orderByAsc(TableConfigColumn::getSort);
        return this.list(wrap);
    }

}
